<template>
	<view class="TUIChat" v-if="conversationType === 'chat'">
		<uni-section title="使用动画效果" type="line">
			<uni-collapse>
				<uni-collapse-item :title="$t('chat.calling')" :show-animation="true" v-if="collapseType">
					<view class="callTop">
						<button class="mini-btn callCenter" type="primary" size="mini"
							@click="joinInGroup()">{{$t('chat.join_call')}}</button>
					</view>
				</uni-collapse-item>
			</uni-collapse>
		</uni-section>
		<!-- 	<view class="more-btn" v-if="conversation?.type === 'GROUP'" @click="handleGetProfile">
			更多</view> -->
		<view class="TUIChat-container" @click="closePop">

			<scroll-view class="TUIChat-main" scroll-y="true" :scroll-with-animation="true" @scroll="closeDig"
				:refresher-triggered="triggered" :refresher-enabled="true" @refresherrefresh="handleRefresher"
				:scroll-top="scrollTop">
				<view class="TUI-message-list" @touchmove="handleTouchStart" @click="closePop" @touchend="touchEnd">
					<view class="loading-text" v-if="isCompleted">{{ $t('chat.chat_no_more_history') }}</view>
					<checkbox-group @change="selectMessages">
						<view v-for="(item, index) in messages" :key="item.ID" :id="'view' + item.ID">
							<view class="time-container"
								v-if="item.showTime && !(item.payload.operationType == 6 && Object.keys(item.payload.newGroupProfile)[0] == 'avatar') ">
								{{
              formatTimeago(item.time * 1000, that)
            }}
							</view>
							<view class="message-item"
								v-if="item.type !== types.MSG_CUSTOM && !(item.payload.operationType == 6 && Object.keys(item.payload.newGroupProfile)[0] == 'avatar')  || (item.type === types.MSG_CUSTOM && messageCustomType(item))">
								<view class="message-item-checkbox">
									<checkbox
										v-if="!item.isRevoked && item.type !== types.MSG_GRP_TIP && isfloat===1&&item.type !== types.MSG_CUSTOM"
										:value="item.ID" />
								</view>
								<MessageTip v-if="!item.isRevoked && item.type === types.MSG_GRP_TIP "
									:data="handleTipMessageShowContext(item)" />
								<!-- <MessageTip v-if="item.type === types.MSG_GRP_SYS_NOTICE" /> -->
								<MessageBubble v-if="!item.isRevoked && item.type !== types.MSG_GRP_TIP"
									:data="handleImgAndName(item)">
									<Message-Operate v-if="dialogID === item.ID" :data="item" @Forward="isFloat"
										@reply="showReplyOrigin" @dict_text="dicttext" @tran_slate="id" :msgid="id1"
										class="dialog dialog-item" :style="{
                  top: dialogPosition.top - 10 + 'px',
                  right: dialogPosition.right + 'px',
                  left: dialogPosition.left + 'px',
                }">
									</Message-Operate>
									<view class="message-item-content">
										<MessageText :id="item.flow + '-' + item.ID" :translate="dicttext1" :msgid="id1"
											v-if="item.type === types.MSG_TEXT"
											:data="handleTextMessageShowContext(item)" :messageData="item"
											@longpress="handleItem($event, item)"></MessageText>
										<MessageImage :id="item.flow + '-' + item.ID"	:imglist="ImgUrlList"
											v-if="item.type === types.MSG_IMAGE"
											:data="handleImageMessageShowContext(item)" :messageData="item"
											@longpress="handleItem($event, item)"
											@click="previewOpen(item.payload.imageInfoArray[0].url.indexOf('https') > -1 ?
											item.payload.imageInfoArray[0].url : item.payload.imageInfoArray[0].imageUrl)"
                      ></MessageImage>
										<MessageVideo :id="item.flow + '-' + item.ID"
											v-if="item.type === types.MSG_VIDEO"
											:data="handleVideoMessageShowContext(item)" :messageData="item"
											@longpress="handleItem($event, item)" 
											@click="previewOpen(item.payload.videoUrl)"/>
										<MessageAudio :id="item.flow + '-' + item.ID"
											v-if="item.type === types.MSG_AUDIO"
											:data="handleAudioMessageShowContext(item)" :messageData="item"
											@longpress="handleItem($event, item)" />
										<MessageFace :id="item.flow + '-' + item.ID" v-if="item.type === types.MSG_FACE"
											:data="handleFaceMessageShowContext(item)" :messageData="item"
											@longpress="handleItem($event, item)" />
										<MessageCustom :id="item.flow + '-' + item.ID"
											v-if="item.type === types.MSG_CUSTOM"
											:data="handleCustomMessageShowContext(item)" :messageData="item"
											@longpress="handleItem($event, item)" />
										<MessageMerger :id="item.flow + '-' + item.ID"
											v-if="item.type === types.MSG_MERGER"
											:data="handleMergerMessageShowContext(item)" :messageData="item"
											@click="godetail(item)" @longpress="handleItem($event, item)" />
										<MessageFile :data="handleFileMessageShowContext(item)"
											@longpress="handleItem($event, item)" :item="item"
											:id="item.flow + '-' + item.ID" v-if="item.type === types.MSG_FILE" />
									</view>
								</MessageBubble>
								<MessageRevoked v-if="item.isRevoked" :data="item" @edit="handleEdit(item)" />
							</view>
						</view>
					</checkbox-group>

				</view>
				<view :style="{ 'height': keyboardHeight + 80 + 'rpx'}"></view>
			</scroll-view>
		</view>
		<view class="messageSelector-box" v-if="isfloat===1">
			<view class="u-flex">
				<view class="icon icon-31zhuanfa mul-btn" @click="transmitMultipleMessages"></view>
				<text class="u-font-26 u-m-r-30"> {{ $t('chat.transfer')}}</text>
			</view>
		<!-- 	<view class="u-flex">
				<view class="icon icon-shanchu mul-btn" @click="deletemsg"></view>
				<text class="u-font-26">{{ $t('chat.btn_del')}}</text>
			</view> -->
		</view>
		<TUIChatInput v-if="isfloat!==1&&stat==1" :text="text" :conversationData="conversation"
			:replyOriginMessage="currentMessage" :isShowOriginReply="showReply" @closeOriginReply="showReplyOrigin"
			ref="chatinput" @alt_bottom="altBottom"></TUIChatInput>
		<TUIChatInputDisable v-if="isfloat!==1&&stat!=1" :text="text" :conversationData="conversation" ref="chatinput"
			@alt_bottom="altBottom"></TUIChatInputDisable>
	</view>
	<view class="TUIChat" v-if="conversationType === 'system'">
		<MessageSystem :data="messages" :types="types" />
	</view>
	 <previewImage ref="previewImage" :opacity="1" :circular="true" :imgs="ImgUrlList"></previewImage>
</template>
<script lang="ts">
	import pageMixin from '@/utils/pageMixin';
	import {
		defineComponent,
		reactive,
		toRefs,
		ref,
		computed,
		nextTick,
		watch,
		onMounted,
		onBeforeUnmount,
		getCurrentInstance
	} from "vue";
	import {
		onShow,
		onReady,
		onLoad,
		onNavigationBarButtonTap,
		onUnload
	} from "@dcloudio/uni-app";

	// 消息元素组件
	import MessageBubble from "./components/message-elements/message-bubble.vue";
	import MessageText from "./components/message-elements/message-text.vue";
	import MessageImage from "./components/message-elements/message-image.vue";
	import MessageOperate from "./components/message-elements/message-operate.vue";
	import MessageVideo from "./components/message-elements/message-video.vue";
	import MessageAudio from "./components/message-elements/message-audio.vue";
	import MessageFace from "./components/message-elements/message-face.vue";
	import MessageCustom from "./components/message-elements/message-custom.vue";
	import MessageTip from "./components/message-elements/message-tip.vue";
	import MessageRevoked from "./components/message-elements/message-revoked.vue";
	import MessageSystem from "./components/message-elements/message-system.vue";
	import MessageMerger from "./components/message-elements/message-merger.vue";
	import MessageFile from "./components/message-elements/message-file.vue";
	// 底部消息发送组件
	import TUIChatInput from "./components/message-input";
	import TUIChatInputDisable from "./components/message-input-disable";
	import store from "../../TUICore/store";
	import {
		handleAvatar,
		handleTextMessageShowContext,
		handleImageMessageShowContext,
		handleVideoMessageShowContext,
		handleAudioMessageShowContext,
		handleFileMessageShowContext,
		handleFaceMessageShowContext,
		handleLocationMessageShowContext,
		handleMergerMessageShowContext,
		handleTipMessageShowContext,
		handleCustomMessageShowContext,
	} from "../../utils/untis";

	import {
		caculateTimeago,
		formatTimeago
	} from "../../utils/date";
	import Vuex from "vuex";
	import {
		useI18n
	} from "vue-i18n";
	import {
		TUIChatServer
	} from "../../TUICore/server";
	// import timStorage from "../../../../utils/tim-storage.js";
	import timStorage from "../../utils/tim-storage.js"
	import previewImage from '@/components/kxj-previewImage/kxj-previewImage.vue'; //引用插件 
	export default defineComponent({
		mixins: [pageMixin],
		name: "TUIChat",
		components: {
			MessageText,
			MessageImage,
			MessageVideo,
			MessageAudio,
			MessageFace,
			MessageCustom,
			MessageBubble,
			MessageTip,
			MessageRevoked,
			MessageSystem,
			TUIChatInput,
			TUIChatInputDisable,
			MessageOperate,
			MessageMerger,
			MessageFile,
			previewImage
		},

		setup(props) {
			const that = getCurrentInstance()
			const timStore = store.state.timStore;
			uni.$TUIKit.TUIChatServer = new TUIChatServer();
			const TUIServer = uni.$TUIKit.TUIChatServer;
			const chatinput = ref(null)
			const left: number | null = 0;
			const right: number | null = 0;
			const defaultDialogPosition = {
				top: -70,
				left,
				right,
			};
			const userInfo = uni.getStorageSync('userInfo')
			const {
				t
			} = useI18n();
			const data = reactive({
				messageList: computed(() => timStore.messageList),
				targetpath: computed(() => timStore.targetpath),
				conversation: computed(() => timStore.conversation),
				triggered: false,
				scrollTop: 0,
				c: {},
				text: "",
				types: uni.$TIM.TYPES,
				currentMessage: {},
				dialogID: "",
				forwardStatus: false,
				imageFlag: false,
				isCompleted: false,
				oldMessageTime: 0,
				dialogPosition: defaultDialogPosition,
				keyboardHeight: 0,
				dicttext1: [],
				path1: {},
				path2: {},
				path3: {},
				path4: {},
				id1: 0,
				ifLongtap: true,
				isfloat: 0,
				forwordlist: [],
				forwordlist1: {},
				ImgUrlList:[],
				selectedMessageIds: [],
				actionPopup: {
					visible: false,
					message: null,
					recallable: false,
					index: null,
				},
				// 消息选择
				messageSelector: {
					visible: false,
					messages: []
				},
				userImgAndName: {},
				collapseType: false,
				groupRoomId: '',
				CallMediaType: '',
				stat: 1,
				showReply: false, //是否在输入框上方展示回复原消息体
				
				
			});
			const listMap = new Map();
			//判断通话信息为3 的时候不显示
			const messageCustomType = (item: any) => {
				const callingmessage = JSON.parse(item.payload.data);
				if (callingmessage.actionType == 3) {
					return false
				} else {
					return true
				}

			};
			//中途加入语音通话方法
			const joinInGroup = () => {
				console.log(
					"data.groupRoomId++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++fffffffffffffffffff" +
					data.groupRoomId)
				const options = {
					roomID: data.groupRoomId,
					groupID: data.conversation.groupProfile.groupID,
					callMediaType: data.CallMediaType, // 语音通话(callMediaType = 1)、视频通话(callMediaType = 2)
				};
				uni.$TUICallKit.joinInGroupCall(options, (res) => {
					if (res.code === 0) {
						console.log('joinInGroupCall success');
					} else {
						console.log(`joinInGroupCall failed, error message = ${res.msg}`);
					}
				})

			}
			// 判断当前会话类型：无/系统会话/正常C2C、群聊
			const conversationType = computed(() => {
				const conversation: any = data.conversation;
				if (!conversation?.conversationID) {
					return "";
				}
				if (conversation?.type === uni.$TIM.TYPES.CONV_SYSTEM) {
					return "system";
				}
				return "chat";
			});
			//图片视频大图预览
      const previewOpen = (e)=> {
      	var param = e
      	console.log(param); 
      	that.proxy.$refs.previewImage.open(param); // 传入当前选中的图片地址或序号
      	return; //如需测试和uni原生预览差别可注释这两行
      }
			// 不展示已删除消息
			const messages = computed(() => {
				var x=0
		   	data.ImgUrlList = []
				// console.log(data.messageList)
				for(var i in data.messageList){
					if(data.messageList[i].type==='TIMImageElem'){
						
						data.ImgUrlList.push({
							type: 'image',
							url: data.messageList[i].payload.imageInfoArray[0].url.indexOf('https') > -1 ? data.messageList[i].payload.imageInfoArray[0].url : data.messageList[i].payload.imageInfoArray[0].imageUrl,
							cover: ''
						
						})
						console.log(data.messageList[i])
					}
					else if(data.messageList[i].type==='TIMVideoFileElem') {
						data.ImgUrlList.push({
							type: 'video',
							url: data.messageList[i].payload.videoUrl,
							cover: data.messageList[i].payload.thumbUrl
						})
					}
				}
				console.log(data.ImgUrlList)
				if (data.messageList.length > 0) {
					data.oldMessageTime = data.messageList[0].time;
					return data.messageList.filter((item: any) => {
						return !item.isDeleted;
					});
				}
			});
			// 获取页面参数
			onLoad((options) => {
				store.commit("timStore/setDeveloptext", "")
				store.commit("timStore/setVoicebody", "")
				setTimeout(() => {
					if (data.conversation.type == 'GROUP') {
						getGroupUserImg(data.conversation.groupProfile.groupID)
						uni.setNavigationBarTitle({
							title: options?.conversationName + '(' + data.conversation
								.groupProfile.memberCount + ')',
						});
						that.proxy.$http.get('/bbs/getUserGroup/getUserGroupRoomId', {
							groupId: data.conversation.groupProfile.groupID
						}).then((res) => {
							if (res.RoomId != '0') {
								data.collapseType = true
								data.groupRoomId = res.RoomId
								data.CallMediaType = res.CallMediaType
							}
						}).catch(err => {})
					} else {
						console.log("data.conversation.userProfile.userID", data.conversation.userProfile.userID)
						getUserImg(data.conversation.userProfile.userID, userInfo.timUserId)
						uni.setNavigationBarTitle({
							title: options?.conversationName,
						});
						//获取用户状态
						getUserStat(data.conversation.userProfile.userID)
					}
					// console.log(data.conversation)
				}, 200)
			});		
			const getGroupUserImg = (groupId) => {
				//从这获取本地头像姓名
				that.proxy.$http.get('/bbs/getUse/GroupImgAndId', {
					groupId: groupId
				}).then((res) => {
					data.userImgAndName = res
				}).catch(err => {})
			};
			const godetail = (e) => {
				var params = {
					lists: JSON.stringify(e.payload.messageList)
				}
				console.log('1111111111111111124' + JSON.stringify(e.payload))
				that.proxy.$goPage('/note/mergerdetail', params)
			};
			const getUserImg = (fromId) => {

				//从这获取本地头像姓名
				that.proxy.$http.get('/bbs/getUse/ImgAndId', {
					fromId: fromId
				}).then((res) => {
					data.userImgAndName = res
				}).catch(err => {})
			};
			const getUserStat = (fromId) => {
				console.log("--------------stat-------------" + fromId);
				//从这获取本地头像姓名
				that.proxy.$http.get('/client/auth/account/stat', {
					fromId: fromId
				}).then((res) => {
					data.stat = res
				}).catch(err => {})
			};
			const handleImgAndName = (item) => {
				if (item.conversationType != 'C2C' && item.conversationType != '' && JSON.stringify(data
						.userImgAndName) !== '{}') {
					//判断对象是否为空,若为空,data.userImgAndName[item.from][0]为undefined,会报错,进入不了聊天页面
					item.nick = data.userImgAndName[item.from][0]
					item.avatar = data.userImgAndName[item.from][1]
				} else if (item.conversationType.to == '') {
					item.nick = data.userImgAndName[item.From][0]
					item.avatar = data.userImgAndName[item.From][1]
				}
				return item
			};
			onUnload(() => {
				TUIServer.destroyed();
			});
			// 监听数据渲染，展示最新一条消息
			watch(messages, (newVal: any, oldVal: any) => {
				for(var i = 0 ;  i< data.messageList.length;i++){
					listMap.set(data.messageList[i].ID,data.messageList[i]);
				}
				//每次来一条消息的时候去获取一下数据库看看是否有语音消息如果有语音消息打开弹窗
				if (data.conversation.type == 'GROUP') {
					that.proxy.$http.get('/bbs/getUserGroup/getUserGroupRoomId', {
						groupId: data.conversation.groupProfile.groupID
					}).then((res) => {
						if (res.RoomId != '0') {
							data.collapseType = true
							data.groupRoomId = res.RoomId
							data.CallMediaType = res.CallMediaType
						} else {
							data.collapseType = false
							data.groupRoomId = ''
							data.CallMediaType = ''
						}
					}).catch(err => {})
				}
				// 下拉刷新不滑动 todo 优化
				nextTick(() => {
					const newLastMessage = newVal[newVal.length - 1];
					const oldLastMessage = oldVal ? oldVal[oldVal.length - 1] : {};
					data.oldMessageTime = messages.value[0].time;
					handleShowTime();
					if (oldVal && newLastMessage.ID !== oldLastMessage.ID) {
						// handleScrollBottom(); // 非从conversationList 首次进入
						// console.log('我要滚动到底部了------------------------------------1')
						setTimeout(() => {
							data.scrollTop = data.scrollTop + 200;
						}, 500);
					}
				});
			});
			// 监听数据初次渲染，展示最新一条消息
			// TODO app 中获取不到DOM 元素
			onReady(() => {
				// 延时 300 ，能完成更新 ！！！  首次进入回话，滑动到底部优化 安卓出现抖动
				// data.scrollTop = 9999;
				// console.log('我要滚动到底部了------------------------------------2')
				setTimeout(() => {
					data.scrollTop = 99999;
				}, 500);
			});

			onMounted(() => {
				handleShowTime();
				// // 监听回退，已读上报
				uni.addInterceptor("navigateBack", {
					success() {
						// 小程序无效 官网链接：https://uniapp.dcloud.io/api/interceptor.html
						// console.log("data.conversation?.conversationID", data.conversation)
						// console.log("data.conversation?.conversationID", data.conversation
						// ?.conversationID)
						uni.$TUIKit.TUIConversationServer.setMessageRead(
							data.conversation?.conversationID
						);
					},
				});
			});


			onNavigationBarButtonTap((e) => {
				if (e.text == 'back') {
					uni.navigateBack()
				} else if (e.type == 'menu') {
					console.log("data.conversation?", data.conversation)
					if (data.conversation?.type === 'C2C') {
						const userId = data.conversation?.userProfile.userID;
						that.proxy.$goPage('/note/room/detail');
					} else if (data.conversation?.type === 'GROUP') {
						that.proxy.$goPage('/note/group/detail', {
							groupId: data.conversation?.groupProfile.groupID,
							groupName: data.conversation?.groupProfile.name,
							pid: props.pid,
						});
					} else {
						uni.showToast({
							title: "暂无信息",
						});
					}
				}
			});
			const deletemsg = () => {

				for (var j = 0; j < data.selectedMessageIds.length; j++) {
					//从Map中根据ID获取item
					var msg = listMap.get(data.selectedMessageIds[j])
					TUIServer.deleteMessage([msg])
					msg.isDeleted = true;
					timStorage.update(msg.id, msg);
					setTimeout(() => {
						data.isfloat = 0;
					}, 100);
				}

			};
			const closeDig = () => {
				data.dialogID = ''
			}
			const altBottom = (e: any) => {
				console.log(e)
				data.keyboardHeight = e
				setTimeout(() => {
					console.log(data.scrollTop)
					data.scrollTop = data.scrollTop + 200;
				}, 100);
			};
			const isFloat = (e: any) => {
				data.isfloat = e
			};
			//在输入框上方展示消息回复的原消息体
			const showReplyOrigin = (e) => {
				console.log('进来chat页面展示原消息体', e)
				data.showReply = e
			};
			const dicttext = (e: any) => {
				data.dicttext1 = e
				data.dialogID = ''
			};
			const id = (e: any) => {
				data.id1 = e
			};
			const handleGetProfile = () => {
				uni.navigateTo({
					url: "../TUIGroup/index",
				});
			};
			const handleShowTime = () => {
				if (messages.value) {
					Array.from(messages.value).forEach((item) => {
						if (item.time - data.oldMessageTime > 5 * 60) {
							data.oldMessageTime = item.time;
							item.showTime = true;
						} else {
							item.showTime = false;
						}
					});
				}
			};
			const selectMessages = (e) => {
				data.selectedMessageIds = e.detail.value;
			};
			const closePop = () => {
				data.dialogID = ''
				chatinput.value.closedPop()
				that.proxy.$refs.chatinput.closedEmoji()
			};
			const handleScrollBottom = () => {
				uni
					.createSelectorQuery()
					.select(".TUI-message-list")
					.boundingClientRect((res) => {
						const scrollH = res.height?.height;
						data.scrollTop = scrollH;
					})
					.exec();
			};

			// 需要自实现下拉加载
			const handleScroll = (e: any) => {
				data.triggered = "restore"; // 需要重置
			};

			const handleRefresher = () => {
				data.triggered = true;
				if (!TUIServer.currentStore.isCompleted) {
					TUIServer.getHistoryMessageList().then((res) => {
						data.triggered = false;
						data.isCompleted = TUIServer.currentStore.isCompleted;
					}).catch(err => {
						data.isCompleted = TUIServer.currentStore.isCompleted;
						console.log(err)
					})
				} else {
					data.isCompleted = true;
				}
				setTimeout(() => {
					data.triggered = false;
				}, 500);
			};

			// 处理需要合并的数据
			const handleSend = (emo: any) => {
				data.text += emo.name;
				// inputEle.value.focus();
			};
			const touchEnd = () => {
				data.ifLongtap = true;
			};
			// 发送消息
			const handleSendTextMessage = (e: any) => {
				if (data.text.trimEnd()) {
					TUIServer.sendTextMessage(JSON.parse(JSON.stringify(data.text)));
				}
				data.text = " ";
			};
			// 右键消息，展示处理功能
			const handleItem = (event: any, item: any) => {
				console.log('dddddddddd')
				if (data.ifLongtap) {
					const {
						flow
					} = item;
					// const { height, top } = event.target.getBoundingClientRect();
					try {
						const query = uni.createSelectorQuery(); // .in(this)
						query
							.select(`#${item.flow + "-" + item.ID}`)
							.boundingClientRect((res: any) => {
								const {
									top
								} = res;
								// 弹框在下面显示，60--弹框高度；44--导航栏高度；20--弹框离信息间距
								if (top < 0) {
									var y = parseInt(top);
									var x = Math.abs(y);
									data.dialogPosition = {
										...data.dialogPosition,
										top: x + 15,
									};
									data.dialogPosition = {
										...data.dialogPosition,
										right: flow === "out" ? 0 : null, // 发出去的消息（弹框 right 都是 0）
										left: flow === "in" ? 0 : null, // 接收的消息（弹框 left 都是 0）
									};
									return
								};
								if (top < 60 + 20 && top > 0) {
									data.dialogPosition = {
										...data.dialogPosition,
										top: -5,
									};
									data.dialogPosition = {
										...data.dialogPosition,
										right: flow === "out" ? 0 : null, // 发出去的消息（弹框 right 都是 0）
										left: flow === "in" ? 0 : null, // 接收的消息（弹框 left 都是 0）
									};
								} else {
									data.dialogPosition = {
										...defaultDialogPosition,
										right: flow === "out" ? 0 : null, // 发出去的消息（弹框 right 都是 0）
										left: flow === "in" ? 0 : null, // 接收的消息（弹框 left 都是 0）
									};
								}
							})
							.exec((res: any) => {
								data.currentMessage = item;
								console.log('currentMessage----------------------------', data
									.currentMessage)
								console.log(
									'data.dialogID------------------------------------------------',
									data.dialogID)
								data.dialogID = item.ID;
							});
					} catch (error) {
						data.currentMessage = item;
						data.dialogID = item.ID;
					}
				}
			};
			async function transmitMultipleMessages() {
				if (data.selectedMessageIds.length > 0) {
					uni.showActionSheet({
						itemList: [t('chat.every_forward'), t('chat.merge_forward')],
						success: function(res) {
							saveVideo(res).then(() => {
								var objstr = JSON.stringify(data.forwordlist1).replace(
									/\&/g, "%26");
								var params = {
									title: "选择好友或群",
									messages: objstr,
									type: 1
								};
								uni.hideToast()
								console.log('dadadadadad',JSON.stringify(params))
								that.proxy.$goPage('/note/transmit', params);
							})
						},
						fail: function(res) {
							console.log(res.errMsg);
						}
					});
				}
				setTimeout(() => {
					data.isfloat = 0;
				}, 500);
			}

			function saveVideo(lists) {
				return new Promise(resolve => {
					if (lists.tapIndex == 0) {
						uni.showToast({
							title: '转发内容加载中',
							icon: 'loading'
						})
						var x = 0;
						for (var j = 0; j < data.selectedMessageIds.length; j++) {
							for (var i = 0; i < data.messageList.length; i++) {
								if (data.messageList[i].ID == data.selectedMessageIds[j]) {
									data.forwordlist1[x++] = data.messageList[i]
								}
							};
						}
						var j = 0;
						var k = 0;
						var a = 0;
						var f = 0;
						var l = 0;
						for (var i = 0; i < x; i++) {
							if (data.forwordlist1[i].type === 'TIMImageElem' && data.forwordlist1[i] !=
								'') {
								var imgUrl = data.forwordlist1[i].payload.imageInfoArray[0].imageUrl
								imgUrl = imgUrl.replace('?imageMogr2/', '')
								uni.downloadFile({
									url: imgUrl,
									success: (res) => {
										if (res.statusCode === 200) {
											uni.saveFile({
												tempFilePath: res.tempFilePath,
												success: function(result) {
													data.path1[j++] = result
														.savedFilePath
													store.commit(
														"timStore/setImagepath",
														data.path1)
													f++
													if (f == x) {
														resolve()
													}
												},
											})
										}
									}
								})
							} else if (data.forwordlist1[i].type === 'TIMVideoFileElem' && data
								.forwordlist1[i] != '') {
								uni.downloadFile({
									url: data.forwordlist1[i].payload.remoteVideoUrl,
									success: (res) => {
										if (res.statusCode === 200) {
											uni.saveFile({
												tempFilePath: res.tempFilePath,
												success: function(result) {
													data.path2[k++] = result
														.savedFilePath
													store.commit(
														"timStore/setVideopath",
														data.path2)
													f++
													if (f == x) {
														resolve()
													}
												},
											})
										}
									}
								})
							} else if (data.forwordlist1[i].type === 'TIMTextElem' && data.forwordlist1[
									i] != '') {
								f++
								if (f == x) {
									resolve()
								}
							}else if (data.forwordlist1[i].type === 'TIMSoundElem' && data.forwordlist1[
									i] != '') {
								uni.downloadFile({
									url: data.forwordlist1[i].payload.remoteAudioUrl,
									success: (res) => {
										if (res.statusCode === 200) {
											uni.saveFile({
												tempFilePath: res.tempFilePath,
												success: function(result) {
													data.path4[l++] = result
														.savedFilePath
													store.commit(
														"timStore/setSoundpath",
														data.path4)
													f++
													if (f == x) {
														resolve()
													}
												},
											})
										}
									}
								})
							}else if (data.forwordlist1[i].type === 'TIMFileElem' && data.forwordlist1[
									i] != '') {
								uni.downloadFile({
									url: data.forwordlist1[i].payload.fileUrl,
									success: (res) => {
										if (res.statusCode === 200) {
											uni.saveFile({
												tempFilePath: res.tempFilePath,
												success: function(result) {
													data.path3[a++] = result
														.savedFilePath
													store.commit(
														"timStore/setFilepath",
														data.path3)
													f++
													if (f == x) {
														resolve()
													}
												},
											})
										}
									}
								})
							}
						}
					}
					if (lists.tapIndex == 1) {
						var x = 0
						for (var j = 0; j < data.selectedMessageIds.length; j++) {
							for (var i = 0; i < data.messageList.length; i++) {
								if (data.messageList[i].ID == data.selectedMessageIds[j]) {
									console.log('合并转发信息+++++++++++++++++++++++++++++++', JSON.stringify(
										data.messageList[i]))
									data.forwordlist[x++] = data.messageList[i]
								}
							};
						}
						//图片地址进行正则转换&字符，否则传过去不完整
						var objstr = JSON.stringify(data.forwordlist).replace(/\&/g, "%26");
						var params = {
							title: "选择好友或群",
							messages: objstr,
							type: 2
						};
						that.proxy.$goPage('/note/transmit', params);
					}
				})

			};
			// 滑动触发时，失焦收起键盘
			const handleTouchStart = () => {
				data.ifLongtap = false;
				uni.hideKeyboard();
			};
			// 重新编辑
			const handleEdit = (item: any) => {
				data.text = item.payload.text;
			};
			return {
				...toRefs(data),
				conversationType,
				messages,
				handleShowTime,
				handleTouchStart,
				handleRefresher,
				handleScroll,
				handleScrollBottom,
				handleSendTextMessage,
				handleItem,
				handleEdit,
				handleTextMessageShowContext,
				handleImageMessageShowContext,
				handleVideoMessageShowContext,
				handleAudioMessageShowContext,
				handleFileMessageShowContext,
				handleFaceMessageShowContext,
				handleLocationMessageShowContext,
				handleMergerMessageShowContext,
				handleTipMessageShowContext,
				handleCustomMessageShowContext,
				handleSend,
				caculateTimeago,
				formatTimeago,
				handleGetProfile,
				that,
				closePop,
				chatinput,
				altBottom,
				dicttext,
				id,
				touchEnd,
				isFloat,
				selectMessages,
				deletemsg,
				transmitMultipleMessages,
				closeDig,
				handleImgAndName,
				messageCustomType,
				godetail,
				joinInGroup,
				showReplyOrigin,
				previewOpen
				// transmitMultipleMessages
			};
		},
	});
</script>
<style lang="scss" scoped>
	@import "../styles/TUIChat.scss";

	.mul-btn {
		display: flex;
		align-items: center;
		font-size: 48rpx;
		margin-right: 20rpx;
	}

	.message-item-checkbox {
		margin: 10rpx 0 0 10rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
	}

	.message-item {
		display: flex;
		margin: -10rpx 0 20rpx 0;
	}

	.messageSelector-box {
		display: flex;
		justify-content: center;
		align-items: center;
		backdrop-filter: blur(0.27rpx);
		width: 100%;
		position: fixed;
		bottom: 0;
		left: 0;
		border-radius: 12rpx;
		background: #f1f1f1;
		height: 90rpx;
		padding: 20rpx 0;
		font-size: 40rpx;
		border-top: 1px solid #e1e4e4;
	}

	.callTop {
		height: 50px;
		width: 100%;
	}

	.callCenter {
		margin-left: 150px;
	}
.full{
		position: relative;
		.btns{
			position: absolute;
			background-color: rgba(255,255,255,0.5);
			z-index: 99999;
			left: 100rpx;
			top: 50rpx;
			right: 100rpx;
			display: flex;
			justify-content: space-around;
			flex-wrap: wrap;
			>view{
				height: 60rpx;
				line-height: 60rpx;
				text-align: center;
				padding: 0 20rpx;
			}
			&.full{
				position: relative;
				left: 0;
				right: 0;
				>view{
					height: 60rpx;
					line-height: 60rpx;
					text-align: center;
					padding: 0 20rpx;
					background-color: rgba(0,0,0,0.1);
					margin-bottom: 10rpx;
				}
			}
		}
	}
</style>
